import os
import sys
import threading
import time
import tkinter as tk
from tkinter import ttk
from PIL import Image, ImageTk

project_root = os.path.dirname(os.path.abspath(__file__))
if project_root not in sys.path:
    sys.path.insert(0, project_root)

from core.main_controller import MainController


class App:
    def __init__(self, root):
        self.root = root
        self.root.title("曈行")
        self.root.geometry("520x360")
        self.controller = None
        self.worker = None
        self.running = False

        style = ttk.Style()
        try:
            style.theme_use("clam")
        except Exception:
            pass

        self.header = ttk.Label(self.root, text="一键启动与状态", font=("Segoe UI", 14))
        self.header.pack(pady=12)

        btn_frame = ttk.Frame(self.root)
        btn_frame.pack(pady=6)
        self.start_btn = ttk.Button(btn_frame, text="启动系统", command=self.start_system)
        self.stop_btn = ttk.Button(btn_frame, text="停止系统", command=self.stop_system, state=tk.DISABLED)
        self.start_btn.grid(row=0, column=0, padx=8)
        self.stop_btn.grid(row=0, column=1, padx=8)

        info_frame = ttk.Frame(self.root)
        info_frame.pack(fill=tk.BOTH, expand=True, padx=16, pady=10)

        self.status_vars = {
            "sys": tk.StringVar(value="系统: 未启动"),
            "conn": tk.StringVar(value="连接: 未连接"),
            "media": tk.StringVar(value="视频流: 未启动"),
            "input": tk.StringVar(value="输入: 未启动"),
            "ultra": tk.StringVar(value="超声波: 未启动"),
            "health": tk.StringVar(value="健康: 未检测"),
            "errors": tk.StringVar(value="错误: 无")
        }

        self.lbl_sys = ttk.Label(info_frame, textvariable=self.status_vars["sys"], font=("Segoe UI", 12))
        self.lbl_conn = ttk.Label(info_frame, textvariable=self.status_vars["conn"], font=("Segoe UI", 12))
        self.lbl_media = ttk.Label(info_frame, textvariable=self.status_vars["media"], font=("Segoe UI", 12))
        self.lbl_input = ttk.Label(info_frame, textvariable=self.status_vars["input"], font=("Segoe UI", 12))
        self.lbl_ultra = ttk.Label(info_frame, textvariable=self.status_vars["ultra"], font=("Segoe UI", 12))
        self.lbl_health = ttk.Label(info_frame, textvariable=self.status_vars["health"], font=("Segoe UI", 12))
        self.lbl_errors = ttk.Label(info_frame, textvariable=self.status_vars["errors"], font=("Segoe UI", 11))

        self.lbl_sys.pack(anchor="w")
        self.lbl_conn.pack(anchor="w")
        self.lbl_media.pack(anchor="w")
        self.lbl_input.pack(anchor="w")
        self.lbl_ultra.pack(anchor="w")
        self.lbl_health.pack(anchor="w")
        self.lbl_errors.pack(anchor="w", pady=(8, 0))

        preview_frame = ttk.Frame(self.root)
        preview_frame.pack(fill=tk.BOTH, expand=True, padx=16, pady=(0, 10))
        self.preview_label = tk.Label(preview_frame)
        self.preview_label.pack(side=tk.RIGHT, anchor="e")
        self.preview_image = None
        self.preview_enabled = False
        self.preview_btn = ttk.Button(btn_frame, text="打开预览", command=self.toggle_preview)
        self.preview_btn.grid(row=0, column=2, padx=8)

        self.root.protocol("WM_DELETE_WINDOW", self.on_close)
        self.root.after(500, self.refresh_status)
        self.root.after(500, self.refresh_preview)

    def start_system(self):
        if self.running:
            return
        try:
            self.controller = MainController()
        except Exception as e:
            self.status_vars["sys"].set(f"系统: 初始化失败")
            self.status_vars["errors"].set(f"错误: {e}")
            return

        def run():
            try:
                self.controller.start()
            except Exception as e:
                self.status_vars["errors"].set(f"错误: {e}")
                self.running = False

        self.worker = threading.Thread(target=run, daemon=True)
        self.worker.start()
        self.running = True
        self.start_btn.configure(state=tk.DISABLED)
        self.stop_btn.configure(state=tk.NORMAL)
        self.status_vars["sys"].set("系统: 启动中")

    def stop_system(self):
        try:
            if self.controller:
                self.controller.stop()
        except Exception:
            pass
        self.running = False
        self.start_btn.configure(state=tk.NORMAL)
        self.stop_btn.configure(state=tk.DISABLED)
        self.status_vars["sys"].set("系统: 已停止")
        self.preview_enabled = False
        self.preview_btn.configure(text="打开预览")

    def refresh_status(self):
        try:
            if self.controller:
                s = self.controller.get_status()
                self.status_vars["sys"].set(f"系统: {'运行中' if s.get('running') else '未启动'}")
                c = s.get("components", {})
                conn = c.get("connection", {}).get("connected", False)
                self.status_vars["conn"].set(f"连接: {'已连接' if conn else '未连接'}")
                streaming = c.get("media", {}).get("streaming", False)
                self.status_vars["media"].set(f"视频流: {'运行中' if streaming else '未启动'}")
                inp = c.get("input", {}).get("running", False)
                self.status_vars["input"].set(f"输入: {'运行中' if inp else '未启动'}")
                m = self.controller.components.get("media") if hasattr(self.controller, "components") else None
                dist = None
                try:
                    if m:
                        dist = m.get_ultrasonic_distance()
                except Exception:
                    dist = None
                if dist is not None:
                    self.status_vars["ultra"].set(f"超声波: {dist:.2f}m")
                else:
                    self.status_vars["ultra"].set("超声波: 无信号")
                h = s.get("health", {})
                ok = []
                for k, v in h.items():
                    ok.append(f"{k}:{v.get('status','unknown')}")
                self.status_vars["health"].set("健康: " + ("，".join(ok) if ok else "未检测"))
                err = c.get("errors", {}).get("summary", "无错误记录")
                one_line = str(err).splitlines()[0] if err else "无错误记录"
                self.status_vars["errors"].set(f"错误: {one_line}")
        except Exception:
            pass
        finally:
            self.root.after(1000, self.refresh_status)

    def toggle_preview(self):
        if not self.controller:
            return
        self.preview_enabled = not self.preview_enabled
        self.preview_btn.configure(text="关闭预览" if self.preview_enabled else "打开预览")

    def refresh_preview(self):
        try:
            if self.controller and self.preview_enabled:
                media = self.controller.components.get("media") if hasattr(self.controller, "components") else None
                if media:
                    ok, frame = media.capture_image()
                    if ok and frame is not None:
                        import cv2
                        rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
                        img = Image.fromarray(rgb)
                        img = img.resize((240, 180))
                        self.preview_image = ImageTk.PhotoImage(img)
                        self.preview_label.configure(image=self.preview_image)
        except Exception:
            pass
        finally:
            self.root.after(100, self.refresh_preview)

    def on_close(self):
        self.stop_system()
        self.root.destroy()


def main():
    root = tk.Tk()
    App(root)
    root.mainloop()


if __name__ == "__main__":
    main()